/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  StaticDebuggingHelpers.m - iPhoneSRV console for Surveyor SRV-1 and SVS 
 *
 *  Created by Nick Kitchener.  Copyright (C) 2009  Surveyor Corporation 
 *            and Nick Kitchener.  All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details (www.gnu.org/licenses)
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#import "StaticDebuggingHelpers.h"

@implementation StaticDebuggingHelpers

//
// 00000000 00000000 00000000 00000000 .................
//
+(void) dumpMemoryArea:(unsigned char*)img len:(int)len toFile:(NSString*)filename {
	
	FILE *trace = fopen([filename UTF8String], "w");
	fprintf(trace, "Size %i\n", len);
	
	int totalBytesToDump = len;
	int hexDumpOffset=0;
	int charDumpOffset=0;
	
	//            01234567890123456789012345678901234567890
	fprintf(trace, "AAAA: 0 1 2 3  4 5 6 7  8 9 A B  C D E F  0123 4567 89AB CDEF\n");
	fprintf(trace, "----: |------- -------- -------- -------| ---- ---- ---- ----\n");
	
	while(totalBytesToDump>0) {
		fprintf(trace, "%4.4x: ", hexDumpOffset);
		
		int bytesToDump = (totalBytesToDump>=16)?16:totalBytesToDump;
		totalBytesToDump-=bytesToDump;
		
		// dump a line
		int hexBytes = bytesToDump;
		int charBytes = bytesToDump;
		
		int hexLinePos=0;
		int linePos=0;
		while(hexBytes--) {
			fprintf(trace, "%2.2x", (img[hexDumpOffset++]));
			hexLinePos+=2;
			linePos+=2;
			if(hexLinePos%8==0) {
				fprintf(trace, " ");
				linePos++;
			}
		}
		
		while(linePos<= 35) {
			fprintf(trace, " ");
			linePos++;
		}
		
		linePos=0;
		while(charBytes--) {
			char c=img[charDumpOffset++];
			fprintf(trace, "%c", (isalnum(c))?c:'.');
			linePos++;
			if(linePos%4==0) {
				fprintf(trace," ");
			}			
		}
		fprintf(trace,"\n");
	}
	fflush(trace);
	fclose(trace);
}

@end
